import { Form,Icon,Input, Select,Button, Radio } from "antd";
import React from "react";
import styles from "../../index.less"
import { getUuid } from "@/utils/utils";
import Sortable from 'sortablejs';
import {arrayMoveImmutable} from 'array-move';
import { formFieldList } from "@/services/formInteraction";

class CollectNode extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      domKey:getUuid(),
      fieldList:[],
      optionContentList:[''],
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
    this.drawDragBox()
  }

  initForm = data => {
    this.getFieldsList()
    this.props.form.setFieldsValue({label:data.label})
    if(data.data){
      this.props.form.setFieldsValue({collectionType:data.data.field.collectionType})
      this.setState({
        optionContentList:data.data.field.fieldCollection
      })
    }
  }

  getFieldsList = async () => {
    const { formId } = this.props
    const res = await formFieldList({formId})
    this.setState({
      fieldList:res
    })
  }

  drawDragBox = () => {
    const that = this;
    const el = document.getElementById('optionContent')
    new Sortable(el, {
      group: {
        name:"optionContent",
        pull:false,
        put:true
      },
      handle:".anticon-unordered-list",
      animation: 150,
      // 结束拖拽
      onEnd: function (/**Event*/evt) {
        const list = JSON.parse(JSON.stringify(that.state.optionContentList))
        const newArray = arrayMoveImmutable(list, evt.oldIndex, evt.newIndex);
        that.setState({
          optionContentList:newArray,
          domKey:getUuid()
        },() => {
          that.drawDragBox()
        })
      },
    });
  }

  changeOptionContent = (value,index) => {
    const list = JSON.parse(JSON.stringify(this.state.optionContentList))
    list[index] = value;
    this.setState({
      optionContentList:list
    })
  }

  removeOptionContent = index => {
    const list = JSON.parse(JSON.stringify(this.state.optionContentList))
    const newList = []
    for(const i in list){
      if(i!= index){
        newList.push(list[i])
      }
    }
    this.setState({
      optionContentList:newList
    })
  }

  addOptionContent = () => {
    const list = JSON.parse(JSON.stringify(this.state.optionContentList))
    list.push("")
    this.setState({
      optionContentList:list,
    })
  }

  checkSave = () => {
    const { optionContentList } = this.state;
    this.props.form.validateFields((error,values) => {
      if(!error){
        let fieldCollection = optionContentList.filter(item => item != '')
        let obj = {
          label:values.label,
          data:{
            field:{
              collectionType:values.collectionType,
              fieldCollection
            }
          }
        }
        this.props.doSave(obj)
      }
    })
  }

  render(){
    const { domKey,optionContentList,fieldList } = this.state;
    const { form:{getFieldDecorator} } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    return(
      <Form {...formItemLayout}>
        <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />基本信息</div>
        <Form.Item label="节点名称">
          {
            getFieldDecorator("label",{rules:[{required:true,message:"请输入"}]})(
              <Input className={styles.inputItem} />
            )
          }
        </Form.Item>
        
        <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />表单中的字段</div>
        <Form.Item label=" " colon={false}>
          <div id='optionContent' key={domKey}>
            {
              optionContentList.map((item,index) => {
                return (
                  <div key={index} className={styles.optionBox} style={{marginBottom:10}}>
                    <Icon type='unordered-list' className={styles.dragIcon} />
                    <Select onChange={(value) => this.changeOptionContent(value,index)} style={{width:300}} value={item}>
                      {
                        fieldList.map(f => {
                          return <Select.Option key={f.id} value={f.id}>{f.name}</Select.Option>
                        })
                      }
                    </Select>
                    <Icon type='delete' className={styles.removeIcon} onClick={() => this.removeOptionContent(index)} />
                  </div>
                )
              })
            }
          </div>
          <Button type='link' icon='plus' style={{marginTop:10}} onClick={this.addOptionContent}>新增</Button>
        </Form.Item>

        <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />字段收集进入下个节点的方式</div>
        <Form.Item label=" " colon={false}>
          {
            getFieldDecorator("collectionType",{initialValue:0})(
              <Radio.Group>
                <Radio value={0}>字段收集完成</Radio>
                <Radio value={1}>必填字段完成</Radio>
              </Radio.Group>
            )
          }
          <div style={{lineHeight:'25px',color:"#a1a1a1"}}>
            <p>注：</p>
            <p>· 字段收集节点进入下一个节点的两种方式，满足用户填完必填字段或此处所有的字段收集的字段全部填写完成；</p>
            <p>· 选择“字段收集完成”，包括了所有的必填字段完成。</p>
          </div>
        </Form.Item>
        <Form.Item label=" " colon={false} >
          <Button type="primary" onClick={this.checkSave}>保存</Button>
        </Form.Item>
      </Form>
    )
  }
}

export default Form.create()(CollectNode)